<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<merchant-select
						v-model="queryData.merchantId"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('risk.terminal_info_register')}:`"
					class="flex-row-container"
					label-width="90px"
				>
					<el-input
						v-model="queryData.terminalInfo"
						clearable
						size="medium"
						style="width: 180px"
						:placeholder="
							$t('risk.please_enter_register_deviceNumber')
						"
						v-input="{ name: 'noEmpty' }"
						oninput="value=value.replace(/[\u4E00-\u9FA5]/g ,'')"
						:disabled="loading"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.createBy')}:`"
					class="flex-row-container"
					label-width="61px"
				>
					<el-input
						v-model="queryData.createdBy"
						clearable
						size="medium"
						style="width: 180px"
						:placeholder="$t('risk.please_enter_createdBy')"
						v-input="{ name: 'symbols' }"
						:disabled="loading"
						@keyup.enter.native="enterSearch"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.createAt')}:`"
					prop="registerTime"
					class="flex-row-container"
					label-width="77px"
				>
					<el-date-picker
						v-model="queryData.registerTime"
						size="medium"
						:picker-options="pickerShortcut2"
						format="yyyy-MM-dd HH:mm:ss"
						type="datetimerange"
						range-separator="-"
						:start-placeholder="$t('common.start_date')"
						:end-placeholder="$t('common.end_date')"
						align="right"
						:clearable="true"
						value-format="timestamp"
						style="width: 430px"
						:default-time="defaultTime"
					></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('602041')"
						type="warning"
						icon="el-icon-folder"
						:disabled="loading"
						size="medium"
						@click="addLabel"
					>
						{{ $t('common.add') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="tableData"
				style="width: 100%"
				:header-cell-style="getRowClass"
				:max-height="tableHeight"
				highlight-current-row
				@sort-change="_changeTableSort"
			>
				<el-table-column
					type="index"
					align="center"
					:label="`${$t('common.serial_number')}`"
					width="120"
				></el-table-column>

				<el-table-column
					prop="merchantId"
					align="center"
					:label="`${$t('common.belong_merchant')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ merchantFilter(scope.row.merchantId) }}
					</template>
				</el-table-column>
				<el-table-column
					prop="terminalInfo"
					align="center"
					:label="`${$t('risk.terminal_info_register')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.terminalInfo || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="createdBy"
					align="center"
					:label="`${$t('common.createBy')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="createdAt"
					align="center"
					:label="`${$t('common.createAt')}`"
					width="180"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="remarks"
					align="center"
					:label="`${$t('common.remark')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.remarks || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="operating"
					align="center"
					:label="`${$t('common.actions')}`"
					width="210"
				>
					<template slot-scope="scope">
						<el-button
							v-if="hasPermission('602042')"
							type="danger"
							icon="el-icon-delete"
							size="medium"
							@click="deleteLabel(scope.row)"
						>
							{{ $t('common.delete') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			:title="`${$t('risk.add_register_device_black_list')}`"
			:visible.sync="dialogFormVisible"
			:destroy-on-close="true"
			width="30%"
			center
			@close="clear"
		>
			<el-divider></el-divider>
			<el-form
				ref="formSub"
				:model="dialogForm"
				:rules="rules"
				label-width="auto"
			>
				<el-form-item
					:label="`${$t('risk.register_device')}:`"
					prop="terminalInfo"
					class="riskclass"
					:rules="[
						{
							required: true,
							validator: validateIp,
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-model.trim="dialogForm.terminalInfo"
						:placeholder="
							$t('risk.please_enter_register_deviceNumber')
						"
						:maxLength="50"
						clearable
						v-input="{ name: 'noEmpty' }"
						oninput="value=value.replace(/[\u4E00-\u9FA5]/g ,'')"
						style="width:100%"
						autocomplete="off"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					prop="merchantId"
				>
					<merchant-select
						v-model="dialogForm.merchantId"
						:placeholder="$t('common.components.select_merchant')"
						style="width:100%"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.components.remark')}:`"
					prop="remarks"
				>
					<el-input
						v-model="dialogForm.remarks"
						:placeholder="$t('common.please_enter')"
						maxlength="50"
						type="textarea"
						style="width:100%"
						v-input="{ name: 'noEmpty' }"
						show-word-limit
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="subAddOrEdit">
					{{ $t('common.save') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'
const setSearchTime = () => [
	dayjs()
		.subtract(0, 'day')
		.startOf('day'),
	dayjs()
		.subtract(0, 'day')
		.endOf('day')
]
export default {
	name: routerNames.blacklistRegisteredEquipment,
	components: { MainContent },
	mixins: [list],
	data() {
		this.search = this.throttle(this.search, 1000)
		this.reset = this.throttle(this.reset, 1000)
		this._changeTableSort = this.throttle(this._changeTableSort, 1000)
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			queryData: {
				registerTime: setSearchTime()
			},
			tableData: [],
			dialogFormVisible: false,
			dialogForm: {},
			detailTableData: [],
			title: '',
			labelName: '',
			id: '',
			page: 1,
			size: 5,
			summary: 0,
			subAddOrEditDisabled: false,
			typeId: 4
		}
	},
	computed: {
		rules() {
			const merchantId = [
				{
					required: true,
					message: this.$t('merchant.merchant_placeholder'),
					trigger: 'blur'
				}
			]
			return {
				merchantId
			}
		}
	},
	mounted() {},
	methods: {
		loadData() {
			this.loading = true
			const create = this.queryData.registerTime || []
			const [startTime, endTime] = create
			const typeId = this.typeId
			this.tableData = []
			const params = {
				...this.queryData,
				startCreatedAt: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				endCreatedAt: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				...this.getParams(params),
				typeId
			}

			delete params.registerTime
			this.$api
				.getWindControlBlacklistquery(params)
				.then((res) => {
					this.loading = false
					const { code, msg } = res
					if (res && code === 200) {
						this.tableData = (res.data && res.data.record) || []
						this.total = (res.data && res.data.totalRecord) || 0
					} else {
						this.$message({
							message: res && msg,
							type: 'error'
						})
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		validateIp(rule, value, callback) {
			let arr = []
			if (value && value.includes('，')) {
				let str = ''
				str = value.replace(/，/g, ',')
				arr = str.split(',')
			} else if (value) {
				arr = value.split(',')
			} else {
				callback(this.$t('risk.required'))
			}
			if (arr.length > 0) {
				const flag = []
				for (let i = 0; i < arr.length; i++) {
					const ele = arr[i]
					if (ele && ele.length > 100) {
						flag.push(i + 1)
					}
				}
				if (flag.length) {
					callback(this.$t('risk.equipment_no_rule'))
				} else {
					callback()
				}
			}
		},
		reset() {
			this.queryData = { registerTime: setSearchTime() }
			this.pageNum = 1
			this.loadData()
		},
		addLabel() {
			this.title = this.$t('common.add')
			this.dialogForm = {}
			if (!this.$store.getters.isZk) {
				this.dialogForm.merchantId = this.$store.getters.merchantInfo.id
			} else {
				this.dialogForm = {
					terminalInfo: undefined,
					merchantId: undefined,
					remarks: undefined
				}
			}
			this.dialogFormVisible = true
		},

		deleteLabel(val) {
			const { id } = val
			this.$confirm(
				`<strong>${this.$t(
					'risk.is_del_register_device_black_tip'
				)}</strong><br/><strong style="color:#D9001B">${this.$t(
					'risk.del_risk_level_warning'
				)}</strong>`,
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning',
					customClass: 'positionIcon'
				}
			)
				.then(() => {
					this.$api.getWindControlBlacklistdel({ id }).then((res) => {
						const { code } = res
						if (res && code === 200) {
							this.$message.success(
								this.$t('common.delete_success')
							)
							this.loadData()
						}
					})
				})
				.catch(() => {})
		},
		subAddOrEdit() {
			const typeId = this.typeId
			const data = { ...this.dialogForm, typeId }
			this.$refs.formSub.validate((valid) => {
				if (valid) {
					if (this.title === this.$t('common.add')) {
						this.$api
							.getWindControlBlacklistadd(data)
							.then((res) => {
								const { code } = res
								if (res && code === 200) {
									this.$message.success(
										this.$t('common.add_success')
									)
									this.pageNum = 1
									this.loadData()
								}
								this.dialogFormVisible = false
								this.disabledDelay(
									'subAddOrEditDisabled',
									false,
									1000
								)
							})
							.catch(() => {})
					}
				}
			})
		},

		clear() {
			this.$refs.formSub.resetFields()
		},
		handleCurrentChangeDialog(val) {
			this.page = val
			this.getMemberMemberInfoByLabelId(this.id)
		},
		handleSizeChangeDialog(val) {
			this.page = 1
			this.size = val
			this.getMemberMemberInfoByLabelId(this.id)
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .tagheight .el-tag {
	height: 24px;
	line-height: 24px;
	min-width: 60px;
}
::v-deep .el-input-number__decrease,
::v-deep .el-input-number__increase {
	display: none;
}
::v-deep .el-input-number--medium .el-input__inner {
	padding: 0 15px;
	text-align: left;
}

.decoration {
	text-decoration: underline;
	cursor: pointer;
}
.fenye {
	text-align: center;
}
.riskclass {
	margin-bottom: 18px;
}
</style>
